package com.cml.dm.engine.context;

import com.cml.dm.admin.service.DmContextInitServiceFactory;
import com.cml.dm.engine.enums.DmEngineInitEnums;
import com.cml.dm.engine.model.Task;
import lombok.Data;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Component
@Data
public class DmContext {
    public static String DM_META_FILE_NAME = "dm.xml";

    public static  List<Task> CUR_TASK_LIST= new ArrayList<>();
    @Resource
    private DmContextInitServiceFactory dmContextInitServiceFactory;

    private static Map<String, ExecutorService> DM_ENGINE_THREAD_POOL = new HashMap<>();

    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    /**
     * 执行初始化动作
     * 1、判断数据库是否存在，如果不存在，创建数据库表
     * 2、根据metaFileName解析元数据信息到数据库
     */
    @PostConstruct
    public void init() throws Exception {
        dmContextInitServiceFactory.getDmContextInitService(DmEngineInitEnums.SQL_INIT.getType()).init();
        dmContextInitServiceFactory.getDmContextInitService(DmEngineInitEnums.META_HANDLER.getType()).init();
        sqlSessionFactory.getConfiguration().setCallSettersOnNulls(true);
    }

    public static ExecutorService getThreadPool(String taskId){
        ExecutorService executorService = DM_ENGINE_THREAD_POOL.get(taskId);
        if(null == executorService){
            getTask(taskId);
        }
        return DM_ENGINE_THREAD_POOL.get(taskId);
    }

    public static Task getTask(String taskId){
        for (Task task : DmContext.CUR_TASK_LIST) {
            if(taskId.equals(task.getId())){
                /**
                 * 初始化线程池
                 */
                if(DmContext.DM_ENGINE_THREAD_POOL.get(task.getId()) == null){
                    DM_ENGINE_THREAD_POOL.put(task.getId(),new ThreadPoolExecutor(task.getThreadNum(), task.getThreadNum(),
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>(200)));
                }
                return task;
            }
        }
       return null;
    }
}
